package com.mdd.common.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.entity.*;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.goods.GoodsCategory;
import com.mdd.common.entity.goods.GoodsCategoryIndex;
import com.mdd.common.entity.goods.GoodsSku;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.order.OrderGoods;
import com.mdd.common.enums.*;
import com.mdd.common.mapper.*;
import com.mdd.common.mapper.goods.GoodsCategoryIndexMapper;
import com.mdd.common.mapper.goods.GoodsCategoryMapper;
import com.mdd.common.mapper.goods.GoodsMapper;
import com.mdd.common.mapper.goods.GoodsSkuMapper;
import com.mdd.common.mapper.log.LogOrderMapper;
import com.mdd.common.mapper.order.OrderGoodsMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.service.BusinessAppService;
import com.mdd.common.service.ILabelIndexService;
import com.mdd.common.service.IRegionService;
import com.mdd.common.util.ListUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.common.validate.business.BusinessApplyValidate;
import com.mdd.common.vo.LabelDataVo;
import com.mdd.common.vo.LabelVo;
import com.mdd.common.vo.business.BusinessDetailVo;
import com.mdd.common.vo.business.BusinessSubmitResultVo;
import com.mdd.common.vo.LoadDataVo;
import com.mdd.common.vo.business.VersionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BusinessAppServiceImpl implements BusinessAppService {

    @Resource
    BusinessCategoryMapper businessCategoryMapper;

    @Resource
    GoodsCategoryMapper goodsCategoryMapper;

    @Resource
    GoodsCategoryIndexMapper goodsCategoryIndexMapper;

    @Resource
    GoodsMapper goodsMapper;

    @Resource
    BusinessMapper businessMapper;

    @Resource
    OrderMapper orderMapper;

    @Resource
    GoodsSkuMapper goodsSkuMapper;

    @Resource
    OrderGoodsMapper orderGoodsMapper;

    @Resource
    LogOrderMapper logOrderMapper;

    @Resource
    BusinessCategoryIndexMapper businessCategoryIndexMapper;

    @Resource
    BusinessCollectMapper businessCollectMapper;

    @Resource
    BusinessFileMapper businessFileMapper;

    @Resource
    IRegionService regionService;

    @Resource
    ILabelIndexService labelIndexService;

    @Override
    public JSONArray list() {
        List<BusinessCategory> list = businessCategoryMapper.selectList(new QueryWrapper<BusinessCategory>().eq("is_delete", 0).orderByDesc("sort").orderByAsc("id"));
        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
        return ListUtils.listToTree(jsonArray, "id", "pid", "children");
    }

    @Override
    public List<VersionVo> getVersionList() {

        GoodsCategory goodsCategory = goodsCategoryMapper.selectOne(new LambdaQueryWrapper<GoodsCategory>().eq(GoodsCategory::getName, GoodsEnum.MENU_TYPE.getMsg()).orderByDesc(GoodsCategory::getSort).last("limit 1"));

        List<GoodsCategoryIndex> categoryIndexList = goodsCategoryIndexMapper.selectList(new QueryWrapper<GoodsCategoryIndex>().eq("category_id", goodsCategory.getId()));

        List<Integer> categoryIds = new ArrayList<>();
        for (GoodsCategoryIndex goodsCategoryIndex : categoryIndexList) {
            categoryIds.add(goodsCategoryIndex.getGoodsId());
        }

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0).orderByDesc(Arrays.asList("sort"));
        if (categoryIds.size() > 0) {
            queryWrapper.in("id", categoryIds);
        } else {
            queryWrapper.apply("1=0");
        }

        List<Goods> goods = goodsMapper.selectList(queryWrapper);
        List<VersionVo> list = new ArrayList<>();
        for (int i = 0; i < goods.size(); i++) {
            VersionVo vo = new VersionVo();
            Goods item = goods.get(i);
            BeanUtils.copyProperties(item, vo);
            vo.setSellPrice(String.valueOf(item.getMinPrice()));
            if (!(item.getMaxPrice().compareTo(item.getMinPrice()) == 0) && item.getSpecType().equals(2)) {
                vo.setSellPrice(item.getMinPrice() + "~" + item.getMaxPrice());
            }
            if (i == 0) {
                vo.setIsSelected(true);
            }
            list.add(vo);
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BusinessSubmitResultVo submitBusiness(BusinessApplyValidate applyValidate) {
        // 商户表插入数据
        Integer businessId = addBusiness(applyValidate);
        applyValidate.setSourceId(businessId + "");
        applyValidate.setSourceType(SourceTypeEnum.BUSINESS_ID.getKey());

        // 添加订单，订单日志
        Order order = addOrder(applyValidate);

        BusinessSubmitResultVo vo = new BusinessSubmitResultVo();
        vo.setOrderId(order.getId());
        vo.setOrderSn(order.getOrderSn());
        vo.setNeedPayMoney(order.getNeedPayMoney());
        return vo;
    }

    @Override
    public BusinessDetailVo detail(Integer id, Integer userId) {
        Business model = businessMapper.selectById(id);
        Assert.notNull(model, "商户不存在");
        model.setVisit(model.getVisit() + 1);
        businessMapper.updateById(model);
        BusinessDetailVo vo = new BusinessDetailVo();
        BeanUtils.copyProperties(model, vo);
        // 门头照处理
        String logoUrl = model.getLogoUrl();
        if (StringUtils.isNotBlank(logoUrl)) {
            List<String> logoUrls = new ArrayList<>();
            logoUrls.add(UrlUtils.toAbsoluteUrl(logoUrl));
            vo.setLogoUrls(logoUrls);
        }
        // 执照处理
        String licenseUrl = model.getLicenseUrl();
        if (StringUtils.isNotBlank(licenseUrl)) {
            List<String> licenseUrls = new ArrayList<>();
            licenseUrls.add(UrlUtils.toAbsoluteUrl(licenseUrl));
            vo.setLicenseUrls(licenseUrls);
        }
        // 微信二维码处理
        String wechatUrl = model.getWechatUrl();
        if (StringUtils.isNotBlank(wechatUrl)) {
            List<String> wechatUrls = new ArrayList<>();
            wechatUrls.add(UrlUtils.toAbsoluteUrl(wechatUrl));
            vo.setWechatUrls(wechatUrls);
        }
        // 商户分类
        LambdaQueryWrapper<BusinessCategoryIndex> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessCategoryIndex::getBusinessId, model.getId());
        queryWrapper.last("limit 1");
        BusinessCategoryIndex categoryIndex = businessCategoryIndexMapper.selectOne(queryWrapper);
        if (Objects.nonNull(categoryIndex)) {
            vo.setCategoryId(categoryIndex.getCategoryId());
            BusinessCategory businessCategory = businessCategoryMapper.selectById(categoryIndex.getCategoryId());

            vo.setCategoryName(Objects.nonNull(businessCategory.getName()) ? businessCategory.getName() : "");
        }

        vo.setWechatUrl(UrlUtils.toAbsoluteUrl(model.getWechatUrl()));
        if (userId != null) {
            // 查询收藏
            LambdaQueryWrapper<BusinessCollect> bcWrapper = new LambdaQueryWrapper<>();
            bcWrapper.eq(BusinessCollect::getBusinessId, id).eq(BusinessCollect::getUserId, userId).eq(BusinessCollect::getStatus, 1).last("limit 1");
            BusinessCollect collect = businessCollectMapper.selectOne(bcWrapper);
            vo.setIsHeart(Objects.nonNull(collect) ? true : false);

            LabelDataVo topStyle = labelIndexService.getLabelInfo(LabelTypeEnum.LABEL_TOP_UP.getKey());

            LabelDataVo categoryStyle = labelIndexService.getLabelInfo(LabelTypeEnum.CATEGORY_LABEL.getKey());
            vo.setTopStyle(topStyle);
            vo.setCategoryStyle(categoryStyle);
        }
        // 查询相册
        List<BusinessFile> bFiles = getBusinessFileList(id);
        List<String> imageUrls = bFiles.stream().map(BusinessFile::getFileUrl).collect(Collectors.toList());
        vo.setImageUrls(imageUrls);

        // 小程序码
        vo.setMiniUrl(UrlUtils.toAbsoluteUrl(model.getMiniUrl()));

        return vo;
    }

    @Override
    public List<BusinessFile> getBusinessFileList(Integer id) {
        LambdaQueryWrapper<BusinessFile> fWrapper = new LambdaQueryWrapper<>();
        fWrapper.eq(BusinessFile::getBusinessId, id).eq(BusinessFile::getIsDelete, 0).eq(BusinessFile::getFileType, AlbumEnum.IMAGE.getCode());

        List<BusinessFile> bFiles = businessFileMapper.selectList(fWrapper);
        bFiles.forEach(item -> {
            item.setFileUrl(UrlUtils.toAbsoluteUrl(item.getFileUrl()));
        });
        return bFiles;
    }

    @Override
    public AjaxResult<Object> getStoreListConfig() {
        Map<String, Object> result = new HashMap<>();
        // 地区
        JSONArray areaList = regionService.getList();
        result.put("areaList", areaList);
        // 商户分类
        List<BusinessCategory> list = businessCategoryMapper.selectList(new QueryWrapper<BusinessCategory>().eq("is_delete", 0).orderByDesc("sort").orderByAsc("id"));
        List<LabelVo> categoryList = new ArrayList<>();
        list.stream().forEach(item -> {
            LabelVo vo = new LabelVo();
            vo.setValue(item.getId() + "");
            vo.setPid(item.getPid() + "");
            vo.setLabel(item.getName());
            categoryList.add(vo);
        });
        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(categoryList));
        result.put("categoryList", ListUtils.listToTree(jsonArray, "value", "pid", "children"));
        return AjaxResult.success(result);
    }

    /**
     * 添加订单 日志
     *
     * @param applyValidate
     */
    private Order addOrder(BusinessApplyValidate applyValidate) {
        Goods goods = goodsMapper.selectById(applyValidate.getGoodId());

        // 订单编号
        String orderSn = orderMapper.randMakeOrderSn("order_sn");

        // 订单
        Order order = new Order();
        order.setOrderSn(orderSn);
        order.setUserId(applyValidate.getUserId());
        order.setOrderSource(applyValidate.getOrderSource());
        order.setOrderType(applyValidate.getOrderType());
        order.setOrderStatus(OrderEnum.ORDER_STATUS_WAIT_PAY.getCode());
        order.setAddress(applyValidate.getAddress());
        order.setAddressMobile(applyValidate.getMobile());
        order.setAddressContent(applyValidate.getInfo());
        order.setMoney(goods.getMaxPrice());
        order.setGoodsMoney(goods.getMaxPrice());
        order.setNeedPayMoney(goods.getMaxPrice());
        order.setGoodsNum(1);
        order.setUpdateTime(TimeUtils.timestamp());
        order.setCreateTime(TimeUtils.timestamp());
        order.setSourceId(applyValidate.getSourceId());
        order.setSourceType(applyValidate.getSourceType());
        orderMapper.insert(order);

        GoodsSku goodsSku = goodsSkuMapper.selectOne(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goods.getId()).last("limit 1"));

        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setUserId(applyValidate.getUserId());
        orderGoods.setOrderId(order.getId());
        orderGoods.setGoodsType(applyValidate.getOrderType());
        orderGoods.setGoodsId(goods.getId());
        orderGoods.setGoodsName(goods.getName());
        orderGoods.setGoodsImage(UrlUtils.toRelativeUrl(goods.getImage()));
        orderGoods.setGoodsCode(goods.getCode());
        orderGoods.setGoodsSkuId(goodsSku.getId());
        orderGoods.setGoodsSkuValue(goodsSku.getSkuValueArr());
        // 商品单价
        orderGoods.setMoney(order.getMoney());
        orderGoods.setNeedPayMoney(order.getNeedPayMoney());
        orderGoods.setGoodsOriginalPrice(goodsSku.getLinePrice());
        orderGoods.setGoodsPrice(goodsSku.getPrice());
        orderGoods.setGoodsNum(order.getGoodsNum());
        // 商品总额
        orderGoods.setGoodsMoney(order.getGoodsMoney());
        orderGoods.setAfterSale(OrderGoodsEnum.AFTER_STATUS_NO.getCode());
        orderGoods.setCreateTime(TimeUtils.timestamp());
        orderGoods.setUpdateTime(TimeUtils.timestamp());
        orderGoodsMapper.insert(orderGoods);

        // 订单日志
        logOrderMapper.add(order.getId(), OrderLogEnum.TYPE_USER.getCode(), OrderLogEnum.CHANNEL_ADD_ORDER.getCode(), applyValidate.getUserId(), OrderLogEnum.CHANNEL_ADD_ORDER.getMsg());

        return order;
    }


    /**
     * 商户表插入数据
     *
     * @param applyValidate
     */
    private Integer addBusiness(BusinessApplyValidate applyValidate) {
        Business business = new Business();
        // 门头照 处理
        List<String> logoUrl = applyValidate.getLogoUrl();
        if (Objects.nonNull(logoUrl) && !logoUrl.isEmpty()) {
            business.setLogoUrl(UrlUtils.toRelativeUrl(logoUrl.get(0)));
        }
        // 证照
        List<String> licenseUrl = applyValidate.getLicenseUrl();
        if (Objects.nonNull(licenseUrl) && !licenseUrl.isEmpty()) {
            business.setLicenseUrl(UrlUtils.toRelativeUrl(licenseUrl.get(0)));
        }
        // 微信二维码
        List<String> wechatUrl = applyValidate.getWechatUrl();
        if (Objects.nonNull(wechatUrl) && !wechatUrl.isEmpty()) {
            business.setWechatUrl(UrlUtils.toRelativeUrl(wechatUrl.get(0)));
        }


        business.setBusinessName(applyValidate.getBusinessName());
        business.setBusinessTime(applyValidate.getBusinessTime());

        business.setProvinceId(applyValidate.getProvinceId());
        business.setCityId(applyValidate.getCityId());
        business.setDistrictId(applyValidate.getDistrictId());

        business.setLatitude(applyValidate.getLatitude());
        business.setLongitude(applyValidate.getLongitude());
        business.setAddress(applyValidate.getAddress());
        business.setInfo(applyValidate.getInfo());

        business.setStatus(applyValidate.getStatus());
        business.setMobile(applyValidate.getMobile());
        business.setWechat(applyValidate.getWechat());

        business.setUserId(applyValidate.getUserId());

        business.setContent(applyValidate.getContent());

        business.setCreateTime(TimeUtils.timestamp());
        business.setUpdateTime(TimeUtils.timestamp());

        businessMapper.insert(business);


        // 商户分类处理
        List<LoadDataVo> categoryList = applyValidate.getCategoryList();
        if (Objects.nonNull(categoryList) && !categoryList.isEmpty()) {
            BusinessCategoryIndex index = new BusinessCategoryIndex();
            index.setBusinessId(business.getId());
            if (categoryList.size() == 1) {
                index.setCategoryId(categoryList.get(0).getValue());
            }
            if (categoryList.size() == 2) {
                index.setCategoryId(categoryList.get(1).getValue());
            }
            businessCategoryIndexMapper.insert(index);
        }

        return business.getId();
    }
}
